import {
    dateFormatter
} from '@/utils/validate'
import {
    getQueryshifts,
    getGroupList,
    getQueryGroupDuties,
    postGroupDuties,
    getGroupDutiesByLastweek,
    getGroupUsers,
    getchargedoctor,
    postchargedoctor,
    getfilmreadingdoctor,
    querygroupsideduites,
    postfilmreadingdoctor
} from "@/api/api-rostering.js"
import store from '@/store'


export default {
    components: {
        // infoEdit
    },
    data() {
        return {
            downloadLoading: false,
            img: '',
            tips: '',
            userGroup: {}, //小组长及普通用户权限时单个组
            group: '',
            groupOptions: [],
            editInfo: {},
            editDateInfo: {},
            editDate: '',
            editWeek: '',
            editDoc: {},
            editType: -1,
            editShow: false,
            firstDayOfThisWeek: null,
            endDayOfWeek: null,
            queryList: {
                dept: "306bd2e6-76bc-4de1-8715-2e5fa63e510b",
                date: "",
                curDocList: [],
                curNumList: []
            },

            docOptions: [], //医生列表
            numOptions: [{
                    id: 0,
                    name: "普通号"
                },
                {
                    id: 1,
                    name: "专家号"
                }
            ],
            deptOptions: [],
            columnName: [
                // "医生",
                // "时间段",
                "星期一",
                "星期二",
                "星期三",
                "星期四",
                "星期五",
                "星期六",
                "星期日"
            ],
            tableData: [],
            // tableDayData: [], //早上数据
            // tableAfterData: [], //下午数据
            curDay: 1, //当前周的第几天
            curTime: 1, //当前时间
            weekDate: [], //一周的日期
            showDateTitle: "",
            timeDialogVisible: false,
            updateDialogVisible: false,
            curMng: "",
            arrangeDayList: [], //上午排班列表获取
            arrangeAfterList: [], //下午排班列表获取
            listFlag: false,
            loading: false, //table加载
            groupUserList: [],
            allList: [],
            shiftList: [],
            userGroup: {},
            weekChargeDoctor: [],
            quaStr: '',
            readStr: '',
            readList: [],
            readDocId: '',
            readDoc: {},
            selectShow: false,
            // shiftList1: [],
            // shiftList2: []
            // timeState: false,//true将来时间 false历史时间

        }
    },
    methods: {
        cancelSet() {
            this.selectShow = false
            this.readDocId = this.readDoc.userId || ''
        },
        submitRead() {
            let i = this.groupOptions.findIndex(item => item.id == this.group)
            let gname = this.groupOptions[i].name || ''
            let data = {
                    FirstDay: dateFormatter(this.weekDate[0], false).replace(/-/g, '/'),
                    GroupId: this.group,
                    bodyObject: {}
                }
                //      "dutyType": 1,
                // "date": "string",
                // "userId": "string",
                // "userName": "string",
                // "groupName": "string",
                // "groupId": "string"
            let ii = this.readList.findIndex(uitem => uitem.userId == this.readDocId)
            this.readDoc = this.readList[ii]
            let obj = {
                userId: this.readDocId,
                // date: dateFormatter(this.weekDate[0], false).replace(/-/g, '/'),
                userName: this.readDoc.userName,
                groupId: this.group,
                groupName: gname,
            }
            data.bodyObject = obj
            console.log('data', data)
            postfilmreadingdoctor(data).then(res => {
                if (!res) return
                this.selectShow = false
                    // this.weekChargeDoctor = res.result
                this.$message({
                    message: '读片人员保存成功',
                    type: 'success',
                    onClose: () => {}
                });
            })
        },
        querygroupsideduites(type) {
            this.quaStr = ''
            this.readStr = ''
            this.readList = []
            let data = {
                groupId: this.group,
                GroupSideDutyType: type
            }
            this.dataLoading = true
            querygroupsideduites(data).then(res => {
                this.dataLoading = false
                if (!res) return
                let arr = []
                let arr2 = []
                for (let item of res.result) {
                    arr.push(item.secondUserName ? item.userName + '/' + item.secondUserName : item.userName)
                    arr2.push({
                        userName: item.userName,
                        userId: item.userId,
                        userGroupId: item.userGroupId,
                        userGroupName: item.userGroupName
                    })
                    if (item.secondUserName) {
                        arr2.push({
                            userName: item.secondUserName,
                            userId: item.secondUserId,
                            userGroupId: item.secondUserGroupId,
                            userGroupName: item.secondUserGroupName
                        })
                    }
                }


                if (type == 1) {
                    this.readStr = arr.join('，')
                    this.readList = this.uniqueFunc(arr2, 'userId')
                        // this.readList = res.result
                } else {
                    this.quaStr = arr.join('，')
                        // this.qualityList = res.result
                }
            }).catch(() => {
                this.dataLoading = false

            })
        },
        unique(arr) {
            return arr.filter((item, index) => {
                console.log(item, index);
                return arr.indexOf(item) == index
            })

        },
        uniqueFunc(arr, uniId) {
            const res = new Map();
            return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1));
        },

        getQueryWorkshifts() {
            this.shiftList = []
            getQueryshifts({
                ShiftType: "Normal",
                groupId: this.group
            }).then(res => {
                if (!res) return
                this.shiftList = res.result
            })
        },
        getTxt(arr, type = false) {
            if (arr.length <= 0) return ''
            let str = []
            for (let item of arr) {
                let txts =
                    '<span style="color:' + (type ? '#f44336' : item.color) + '">' +
                    item.shiftName +
                    '</span>'
                str.push(txts)
            }
            // console.log(str)
            return str.join('<span>+</span>')
        },
        toExcel() {
            this.downloadLoading = true
            import ('@/vendor/Export2Excel').then(excel => {
                let tHeader = ['日期']
                let filterVal = ['userName']
                for (let i in this.weekDate) {
                    tHeader.push(this.weekDate[i])
                    filterVal.push(i)
                }
                console.log('tHeader', tHeader, filterVal)
                    // const tHeader = ['排班日期', '开始时间', '结束时间', '排班人员']
                    // const list = [...this.tableData.sort(this.compare('startTime', 'endTime', 'date'))]
                    // console.log('list', list)
                const data = this.formatJson(filterVal, this.tableData)
                excel.export_json_to_excel({
                    header: tHeader,
                    data,
                    filename: this.fileTitle,
                    autoWidth: true,
                    bookType: 'xlsx'
                })
                this.downloadLoading = false
            })
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => {
                // console.log(j, v, v[j])
                if (j === 'userName') {
                    return v[j]
                } else {
                    // console.log(j, v.items)
                    // return v.items[j].shiftName || ''
                    let str = []
                    let arr = v.items[j].detail
                    if (arr.length > 0) {
                        for (let iitem of arr) {
                            str.push(iitem.shiftName)
                        }
                    }
                    return str.join('+') || ''
                }
            }))
        },
        getfilmreadingdoctor() {
            this.readDocId = ''
            this.readDoc = ''

            let data = {
                    FirstDay: dateFormatter(this.weekDate[0], false).replace(/-/g, '/'),
                    GroupId: this.group,
                }
                // console.log('data', data)
            getfilmreadingdoctor(data).then(res => {
                if (!res) return
                this.readDoc = res.result || ''
                this.readDocId = !res.result ? '' : res.result.userId
            })
        },
        //获取责任医生
        getchargedoctor() {
            let data = {
                    FirstDay: dateFormatter(this.weekDate[0], false).replace(/-/g, '/'),
                    GroupId: this.group,
                }
                // console.log('data', data)
            getchargedoctor(data).then(res => {
                if (!res) return
                this.weekChargeDoctor = res.result
            })
        },
        getQueryshifts() {
            this.allList = []
            this.tips = ''
            getQueryshifts({
                groupId: this.group
            }).then(res => {
                if (!res) return
                for (let item of res.result) {
                    item.isChecked = false
                }
                this.allList = res.result
                if (res.result.length < 1) {
                    this.tips = '无'
                    return
                }
                for (let i = 0; i < res.result.length; i++) {
                    this.tips +=
                        "<div>" +
                        res.result[i].shiftName +
                        "：" +
                        res.result[i].startTime +
                        "~" +
                        res.result[i].endTime +
                        (res.result[i].isNextDay ? '(次日)' : '') +
                        "</div>";
                }
            })
        },
        // 获取组员
        getGroupUsers() {
            let data = {
                id: this.group,
            }
            getGroupUsers(data).then(res => {
                if (!res) return
                this.groupUserList = res.result.users
                    // that.selectedAxpertName = JSON.parse(JSON.stringify(res.result.users).replace(/userName/g, 'userName'))
            })
        },
        changeGroup() {
            this.tableData = []
            this.tips = ''
            this.getQueryshifts()
            this.getGroupUsers();
            this.getQueryGroupDuties()
            this.getQueryWorkshifts()
        },
        saveSchedule() {
            this.postGroupDuties()
            this.postchargedoctor()
        },
        postchargedoctor() {
            // console.log('ssss', this.weekChargeDoctor)
            let wi = this.weekChargeDoctor.findIndex(wdoc => !!wdoc.userId)
            if (wi < 0) return
            let i = this.groupOptions.findIndex(item => item.id == this.group)
            let gname = this.groupOptions[i].name || ''

            let data = {
                FirstDay: dateFormatter(this.weekDate[0], false).replace(/-/g, '/'),
                GroupId: this.group,
                bodyObject: []
            }
            let tdata = []
            for (let item of this.weekChargeDoctor) {
                if (item.userId) {
                    let ii = this.groupUserList.findIndex(uitem => uitem.id == item.userId)
                    let uname = this.groupUserList[ii].userName || ''
                    let obj = {
                        ...item,
                        ... {
                            userName: uname,
                            groupId: this.group,
                            groupName: gname
                        }
                    }
                    tdata.push(obj)
                }
            }

            data.bodyObject = tdata
                // console.log('data', tdata, data)
            postchargedoctor(data).then(res => {
                if (!res) return
                    // this.loading = true
                    // this.$message({
                    //   message: '排班信息提交成功！',
                    //   type: 'success',
                    //   onClose: () => {}
                    // });
            })
        },
        postGroupDuties() {
            let data = {
                FirstDay: dateFormatter(this.weekDate[0], false).replace(/-/g, '/'),
                GroupId: this.group,
                bodyObject: []
            }
            let tdata = []
            for (let item of this.tableData) {
                let obj = {}

                let arr2 = item.items.filter(iitem => {
                        if (iitem.detail.length > 0) {
                            return iitem
                        }
                    })
                    // console.log('aaa', arr2)
                if (arr2.length > 0) {
                    for (let i = 0; i < arr2.length; i++) {
                        for (let j = 0; j < arr2[i].detail.length; j++) {
                            delete arr2[i].detail[j].shiftType
                        }
                    }
                    obj = {
                        userName: item.userName,
                        items: arr2
                    }
                }
                if (!!obj.userName) {
                    tdata.push(obj)
                }
            }
            // console.log('aaa', tdata)
            // if (tdata.length <= 0) {
            //   this.$message({
            //     message: '无排班信息！',
            //     type: 'warning',
            //     onClose: () => {}
            //   });
            //   return
            // }
            data.bodyObject = tdata
                // console.log('data', tdata, data)
            postGroupDuties(data).then(res => {
                if (!res) return
                    // this.loading = true
                this.getQueryGroupDuties()
                this.$message({
                    message: '排班信息提交成功！',
                    type: 'success',
                    onClose: () => {}
                });
            })
        },
        getGroupDutiesByLastweek() {
            // this.tableData = []
            let data = {
                FirstDay: dateFormatter(this.weekDate[0], false).replace(/-/g, '/'),
                GroupId: this.group
            }
            this.loading = true
            getGroupDutiesByLastweek(data).then(res => {
                // this.loading = false

                if (!res) {
                    this.loading = false
                    return
                }
                for (let item of res.result) {
                    // item.week = this.getWeekDate(item.date)
                    for (let iitem of item.items) {
                        iitem.visible = false
                    }
                }
                this.tableData = res.result

                // if (this.tableData.length > 0) {
                //   this.splitTableData()
                // }
                this.loading = false
            }).catch(() => {

                this.loading = false
            })
        },
        getQueryGroupDuties() {
            this.selectShow = false
                // this.tableData.length = 0
            if (this.group == '') {
                return
            }
            this.getchargedoctor()
            this.getfilmreadingdoctor()
            this.querygroupsideduites(0)
            this.querygroupsideduites(1)
            let data = {
                FirstDay: dateFormatter(this.weekDate[0], false).replace(/-/g, '/'),
                GroupId: this.group
            }
            this.loading = true
            getQueryGroupDuties(data).then(res => {
                // this.loading = false
                // console.log('res', !res)
                if (!res) {
                    this.loading = false
                    return
                }

                for (let item of res.result) {
                    // item.week = this.getWeekDate(item.date)
                    for (let iitem of item.items) {
                        iitem.visible = false
                    }
                }
                this.tableData = res.result

                // if (this.tableData.length > 0) {
                //   this.splitTableData()
                // }
                this.loading = false
            }).catch(() => {
                this.loading = false
            })
        },
        computedData(data) {
            // console.log('ddd', data)
            let arr = {}

            this.groupUserList.forEach(item => {
                // console.log('computedData', item.userName)
                arr[item.userName] = []
                for (let date of this.weekDate) {
                    arr[item.userName][date] = ''
                }

            })
            console.log('computedData', arr)
        },
        getWeekDate(date) {
            let now = new Date(date)
            let day = now.getDay()
            let weeks = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")
            let week = weeks[day]
            return week
        },
        // //拆分数据为上下午
        // splitTableData() {
        //   console.log('sss', this.tableData.sort(this.compare('startTime', 'endTime', 'date')))
        //   this.tableDayData = [...this.tableData.sort(this.compare('startTime', 'endTime', 'date'))]
        // },
        compare(property, property2, property3) {
            console.log('property', property, property2)
            return function(a, b) {
                let value5 = dateFormatter(a[property3], false)
                let value6 = dateFormatter(b[property3], false)
                let value1 = a[property]
                let value2 = b[property]
                let value3 = a[property2]
                let value4 = b[property2]
                console.log('property-ab', value1, value2, value3, value4, value5, value6)
                if (value5 === value6 && value1 === value2) {
                    return value3 > value4 ? 1 : -1
                } else if (value5 === value6) {
                    return value1 > value2 ? 1 : -1
                } else {
                    return value5 > value6 ? 1 : -1
                }
            }
        },
        closeEdit() {
            this.editShow = false
        },
        // confirmDelete(info) {
        //   // console.log(dateFormatter(date, false))
        //   this.editShow = false
        //   if (info.startTime < '24:00') {
        //     let idx = this.tableDayData.findIndex(item => item.id == info.id)
        //     if (idx != -1) {
        //       this.tableDayData.splice(idx, 1)
        //     }
        //   } else {
        //     let idx = this.tableAfterData.findIndex(item => item.id == info.id)
        //     if (idx != -1) {
        //       this.tableAfterData.splice(idx, 1)
        //     }
        //   }
        // },
        confirmEdit(info) {
            if (JSON.stringify(info) == '{}') {
                this.editShow = false
                return
            }
            // console.log('dfss', info)

            this.editShow = false
                // this.$message.success('修改成功')
                // if (info.startTime < '24:00') {
            let idx = this.tableData.findIndex(item => item.id == info.id)
            if (idx != -1) {
                this.tableData.splice(idx, 1, info)
            } else {
                this.tableData.push(info)
            }
            // } else {
            //   let idx = this.tableAfterData.findIndex(item => item.id == info.id)
            //   if (idx != -1) {
            //     this.tableAfterData.splice(idx, 1, info)
            //   } else {
            //     this.tableAfterData.push(info)
            //   }
            // }

            // if (this.calendarEvents.length <= 0) {
            //   this.calendarEvents.push(info)
            // } else {
            //   this.calendarEvents.forEach((item, index, arr) => {
            //     let i = this.calendarEvents.findIndex(item => dateFormatter(item.start, false) == dateFormatter(info.start, false))
            //     // console.log('item', i)

            //     if (i >= 0) {
            //       arr[i].title = info.title
            //       // arr[i].textColor = info.textColor
            //     } else {
            //       this.calendarEvents.push(info)
            //     }
            //   });
            // }
        },
        getFirstDayOfWeek(date) {
            var weekday = date.getDay() || 7; //获取星期几,getDay()返回值是 0（周日） 到 6（周六） 之间的一个整数。0||7为7，即weekday的值为1-7

            date.setDate(date.getDate() - weekday + 1); //往前算（weekday-1）天，年份、月份会自动变化
            this.firstDayOfThisWeek = new Date(date)
                // this.endDayOfWeek = dateFormatter(new Date(date.getTime() + 3600 * 1000 * 24 * 7), false).replace(/-/g, '/')
        },
        init() {
            //时间控件默认赋值
            this.userGroup = store.getters.userInfo
            this.queryList.date = new Date()
            this.getGroupList()
                // this.getQueryshifts()
                //得到当前日期
            this.getCurDay();
            // this.getQueryGroupDuties()
            //  check所有号源
            // this.numOptions.forEach(value => {
            //   this.queryList.curNumList.push(value.name)
            // })
        },
        newId() {
            return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
                (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
            )
        },
        getGroupList() {
            this.loading = true
            getGroupList().then(res => {
                if (!res) return
                this.groupOptions = res.result
                this.group = this.userGroup.groupId || res.result[0].id
                this.getQueryGroupDuties()
                this.getQueryWorkshifts()
                this.getGroupUsers()
                this.getQueryshifts()
            })
        },
        handleDeleteArrange(workTime, id) {
            this.$confirm('此操作将删除该排班, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteData(id)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        deleteData(id) {
            let index;
            if (id) {
                index = this.tableData.findIndex(item => item.id == id);
                this.tableData.splice(index, 1)
            }
        },
        getCurDay() {
            var date = new Date();
            var day = date.getDay(); //周
            this.curDay = day;
            this.curTime = new Date().getTime();
            //计算一周日期
            this.calWeekDay(this.curDay, this.curTime);
        },
        calWeekDay(day, time) {
            let first = day - 1;
            let last = day - 7;
            this.weekDate.length = 0; //先清空
            for (let i = first; i >= last; i--) {
                let newTime = time - 24 * 60 * 60 * 1000 * i;
                this.getFormatDate(newTime, i == first);
                // if(i = first){
                //   this.getWeekNum(newTime)
                // }

            }
        },
        getFormatDate(newTime, type) {
            var date = new Date(newTime);
            var seperator1 = "/";
            var seperator2 = ":";
            var year = date.getFullYear(); //年
            var month = date.getMonth() + 1; //月
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            var strDate = date.getDate(); //日
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = year + seperator1 + month + seperator1 + strDate;
            //一周的日期
            this.weekDate.push(currentdate);
            this.weekChargeDoctor.push({
                dutyType: 5,
                date: currentdate,
                userId: '',
                userName: '',
                groupName: '',
                groupId: this.group,
                id: '',
            })
            if (type) {
                var getDate = this.getMonthWeek(year, month, strDate);
                this.showDateTitle =
                    getDate.getYear +
                    "年 " +
                    getDate.getMonth +
                    "月 第" +
                    getDate.getWeek +
                    "周";
            }
        },
        //得到本月的第几周
        getMonthWeek(a, b, c) {
            console.log('aaa', a, b, c)
                /**
                 * a = d = 当前日期
                 * b = 6 - w = 当前周的还有几天过完(不算今天)
                 * a + b 的和在除以7 就是当天是当前月份的第几周
                 */
            var date = new Date(a, parseInt(b) - 1, parseInt(c)),
                w = date.getDay(),
                d = date.getDate();
            if (w == 0) {
                w = 7;
            }
            // debugger
            var config = {
                getMonth: date.getMonth() + 1,
                getYear: date.getFullYear(),
                getWeek: Math.ceil((d + 6 - w) / 7)
            };
            // console.log('v', config)
            return config;
        },
        //获取上周一周日期
        getLastWeek() {
            this.queryList.date = new Date(this.queryList.date.getTime() - (1000 * 60 * 60 * 24 * 7))
            this.curDay += 7;
            this.calWeekDay(this.curDay, this.curTime);
            this.getQueryGroupDuties();
        },
        //获取下周一周日期
        getNextWeek() {
            this.queryList.date = new Date(this.queryList.date.getTime() + (1000 * 60 * 60 * 24 * 7))
            this.curDay -= 7;
            this.calWeekDay(this.curDay, this.curTime);
            this.getQueryGroupDuties();
        },
        //导入上周数据
        importLastWeek() {
            this.getGroupDutiesByLastweek()
        },
        //获取对话框更改以后的信息 页面信息更新
        // updateInfo(info) {
        //   this.$message.success('修改成功')
        //   //前端直接找到id更改数据
        //   let idx;
        //   let tempObj = Object.assign({}, info);
        //   tempObj.startTime = tempObj.day.slice(0, 10) + ' ' + tempObj.startTime
        //   tempObj.endTime = tempObj.day.slice(0, 10) + ' ' + tempObj.endTime
        //   if (info.workTime == '上午') {
        //     idx = this.tableDayData.findIndex(item => item.id == info.id)
        //     if (idx != -1) {
        //       this.tableDayData.splice(idx, 1, tempObj)
        //     }
        //   } else if (info.workTime == '下午') {
        //     idx = this.tableAfterData.findIndex(item => item.id == info.id)
        //     if (idx != -1) {
        //       this.tableAfterData.splice(idx, 1, tempObj)
        //     }
        //   }
        // },
    },
    computed: {
        // shiftList() {
        //   return [{
        //       label: '班别',
        //       options: [...this.shiftList1]
        //     },
        //     {
        //       label: '不排班',
        //       options: [...this.shiftList2]
        //     }
        //   ]
        // },
        // allList() {
        //   return [...this.shiftList1, ...this.shiftList2]
        // },
        ifNow() {
            let str1 = dateFormatter(new Date(), false)
            let str2 = dateFormatter(this.queryList.date, false)
            if (str1 === str2) {
                return true
            } else {
                return false
            }
        },
        fileTitle() {
            // let date = new Date(this.dateView)
            // let year = date.getFullYear()
            // let month = date.getMonth() + 1
            // let i = this.groupOptions.findIndex(item => item.id == this.group)
            // return `${this.weekDate[0]} - ${this.weekDate[6]} ${this.groupOptions[i].name} 组内排班表`
            return this.showDateTitle + '审核排班表'
        }
    },
    filters: {

    },
    created() {},
    watch: {}
}
